package org.demo.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * 读写属性文件的工具类
 * @author  
 * @date    2011-1-18
 * @file    org.demo.util.PropertyUtil.java
 */
public class PropertyUtil {

	private String filePath;
	
	private Properties properties;
	
	public PropertyUtil(){
	}
	/**
	 * 构造函数
	 * @param filePath
	 */
	public PropertyUtil(String filePath){
		init(filePath);
	}
	/**
	 * 初始化
	 * @param filePath
	 */
	public void init(String filePath){
		// 
		this.filePath = filePath;
		properties = new Properties();
		
		// 
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(filePath);
			properties.load(fis);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {if (fis != null){fis.close();}}catch(Exception e){}
		}
	}
	/**
	 * 保存到磁盘
	 * @return
	 */
	public boolean save(){
		if (filePath == null || properties == null){
			return false;
		}
		// 
		boolean result = true;
		File file = new File(filePath);
		FileOutputStream fos = null;
		// 
		try {
			if (!file.exists()){
				file.createNewFile();
			}
			fos = new FileOutputStream(file);
			properties.store(fos, "##");
		} catch (Exception e){
			result = false;
			e.printStackTrace();
		}
		// 
		return result;
	}
	/**
	 * 获取属性值
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public String getString(String key, String defaultValue){
		return properties.getProperty(key, defaultValue);
	}
	/**
	 * 获取属性值
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public int getInt(String key, int defaultValue){
		String value = properties.getProperty(key);
		int result = defaultValue;
		try {
			result = Integer.parseInt(value);
		} catch(NumberFormatException e){
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 设置属性值
	 * @param key
	 * @param value
	 */
	public void setString(String key, String value){
		properties.setProperty(key, value);
	}
}
